<template>
  <!-- 遏制措施的实施过程表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="840px"
    draggable
    @close="closeDialog"
    :append-to-body="true"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="160">
      <el-row>
        <el-col :span="10">
          <el-form-item label="开始执行时间" prop="startTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.startTime"
              disabled
            />

            <span v-else>{{ formData.startTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="完成时间" prop="lastUpdateTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdateTime"
              disabled
            />

            <span v-else>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <table cellpadding="0" cellspacing="0">
      <tr>
        <td>
          <table
            border="1"
            class="bordered-table"
            cellpadding="5"
            cellspacing="0"
            width="800px"
            style="height: 450px"
          >
            <thead>
              <tr>
                <th rowspan="2"></th>
                <th rowspan="2">地点</th>
                <th rowspan="2">零件号</th>
                <th rowspan="2">数量</th>
                <th rowspan="2">问题件数量</th>
                <th rowspan="2">不良率</th>
              </tr>
            </thead>
            <tbody align="center">
              <template v-for="(i, index) in formData.table" :key="index">
                <tr v-if="isFirstInGroup(index)">
                  <td :rowspan="getRowspan(index)">
                    {{
                      dictionaryStore.filterDictName(
                        "ImProcessType",
                        i.implementationProcessType
                      )
                    }}
                  </td>
                  <td>
                    {{
                      dictionaryStore.filterDictName(
                        "ImProcessSubType",
                        i.implementationProcessSubType
                      )
                    }}
                  </td>
                  <td>
                    <input
                      type="text"
                      v-model="i.materialCode"
                      class="centered-input"
                      maxlength="10"
                    />
                  </td>
                  <td>
                    <input
                      type="text"
                      v-model.number="i.totalQuantity"
                      @input="updateDefectRate(i)"
                      class="centered-input"
                      maxlength="10"
                    />
                  </td>
                  <td>
                    <input
                      type="text"
                      v-model.number="i.exceptionQuantity"
                      @input="updateDefectRate(i)"
                      class="centered-input"
                      maxlength="10"
                    />
                  </td>
                  <td>{{ calculateDefectRate(i) }}%</td>
                </tr>
                <tr v-else>
                  <td>
                    {{
                      dictionaryStore.filterDictName(
                        "ImProcessSubType",
                        i.implementationProcessSubType
                      )
                    }}
                  </td>
                  <td>
                    <input
                      type="text"
                      v-model="i.materialCode"
                      class="centered-input"
                      maxlength="10"
                    />
                  </td>
                  <td>
                    <input
                      type="text"
                      v-model.number="i.totalQuantity"
                      @input="updateDefectRate(i)"
                      class="centered-input"
                      maxlength="10"
                    />
                  </td>
                  <td>
                    <input
                      type="text"
                      v-model.number="i.exceptionQuantity"
                      @input="updateDefectRate(i)"
                      class="centered-input"
                      maxlength="10"
                    />
                  </td>
                  <td>{{ calculateDefectRate(i) }}%</td>
                </tr>
              </template>
            </tbody>
          </table>
        </td>
      </tr>
    </table>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="success"
          :loading="loading"
          @click="handleSubmit(1)"
          >提 交</el-button
        >
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit(0)"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQ8DD3A3ADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  qualityExceptionId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  qualityExceptionCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  implementationProcessType: [],
  implementationProcessSubType: [],
  materialCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  totalQuantity: [],
  exceptionQuantity: [],
  noaQuantity: [],
  version: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  qualityExceptionId: "",
  qualityExceptionCode: "",
  workOrderId: "",
  implementationProcessType: "",
  implementationProcessSubType: "",
  materialCode: "",
  totalQuantity: "",
  exceptionQuantity: "",
  noaQuantity: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  table: [],
  startTime: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        qualityExceptionId,
        qualityExceptionCode,
        workOrderId,
        implementationProcessType,
        implementationProcessSubType,
        materialCode,
        totalQuantity,
        exceptionQuantity,
        noaQuantity,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        qualityExceptionId,
        qualityExceptionCode,
        workOrderId,
        implementationProcessType,
        implementationProcessSubType,
        materialCode,
        totalQuantity,
        exceptionQuantity,
        noaQuantity,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      formData.qualityExceptionId = newVal.qualityProblemId;
      formData.qualityExceptionCode = newVal.qualityProblemCode;
      formData.workOrderId = newVal.id;
      //formData.qualityExceptionId = newVal.id;
      setD3a3();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.qualityExceptionId = "";
  formData.qualityExceptionCode = "";
  formData.workOrderId = "";
  formData.implementationProcessType = "";
  formData.implementationProcessSubType = "";
  formData.materialCode = "";
  formData.totalQuantity = "";
  formData.exceptionQuantity = "";
  formData.noaQuantity = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.table = [];
  formData.startTime = "";
}

const loading = ref(false);

/** 遏制措施的实施过程保存提交 */
async function handleSubmit(state: Number) {
  loading.value = true;
  formData.table[0].version = state;
  let data = await request({
    url: "/qms/q8dd3a3/save",
    method: "post",
    data: formData.table,
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(`成功`);
  closeDialog();
  emit("reset-table", formData.workOrderId);
}
async function setD3a3() {
  let data = await request({
    url: "/qms/q8dd3a3/setD3a3",
    method: "post",
    data: {
      qualityExceptionId: formData.qualityExceptionId,
      workOrderId: formData.workOrderId,
    },
  }).finally(() => {
    loading.value = false;
  });
  formData.table = data.data;
  formData.startTime = formData.table[0].startTime;
  formData.lastUpdateTime = formData.table[0].planDate;
  console.log(formData.table);
}
async function getD3a1() {
  let data = await request({
    url: "/qms/q8dd3a1/getD3a1",
    method: "post",
    data: {
      qualityExceptionId: formData.qualityExceptionId,
      workOrderId: formData.workOrderId,
    },
  }).finally(() => {
    loading.value = false;
  });
  formData.startTime = data.data.exceptionContent;
  console.log(formData.startTime);
}
function updateDefectRate(item) {
  // 更新不良率并将其赋值给 formData.table 中的 noaQuantity 字段
  item.noaQuantity = Number(calculateDefectRate(item)); // 确保将不良率转换为数字类型
}
function calculateDefectRate(item) {
  // 计算不良率：问题件数量 / 总数量
  if (item.totalQuantity > 0) {
    return ((item.exceptionQuantity / item.totalQuantity) * 100).toFixed(2); // 保留两位小数
  }
  return 0; // 当总数量为0时，不良率为0%
}
function isFirstInGroup(index) {
  return (
    index === 0 ||
    formData.table[index].implementationProcessType !==
      formData.table[index - 1].implementationProcessType
  );
}
function getRowspan(index) {
  let count = 1;
  const currentType = formData.table[index].implementationProcessType;
  while (
    index + count < formData.table.length &&
    formData.table[index + count].implementationProcessType === currentType
  ) {
    count++;
  }
  return count;
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style>
.bordered-table {
  width: 800px;
  height: 450px;
  border-collapse: collapse;
}
.bordered-table th,
.bordered-table td {
  border: 1px solid black;
  padding: 5px;
}
.centered-input {
  text-align: center; /* 水平居中 */
}
</style>
